package 示例代码.sence;


import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 模拟一场考试，100名学生
 * 考试时间为120分钟，
 * 30分钟后才可交卷，
 * 当时间到了，或学生都交完卷了考试结束。
 */
public class Exam {

    public static void main(String[] args) {
        DelayQueue<Student> students = new DelayQueue<>();
        for (int i = 0; i < 100; i++) {
            students.add(new Student("code-"+i));
        }
        try {
            Student student;
            while((student = students.take()) != null){
                System.out.println(student.getCode() +"完成考试，耗时："
                        +student.getTime()+"秒");
            }
            System.out.println("所有考生均完成考试");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class Student implements Delayed{

        // 学生编号
        private String code;

        private long time;
        // 考生答题时长,秒
        private long submitTime;

        public Student(String code) {
            this.code = code;
            time = (long) (Math.random()*120);
            this.submitTime = (long) (time + System.currentTimeMillis()/1000);
        }

        @Override
        public int compareTo(Delayed o) {
            if(o == null||! (o instanceof Student)) return 1;
            if(o == this) return 0;
            if(this.getDelay(TimeUnit.MILLISECONDS) == o.getDelay(TimeUnit.MILLISECONDS)) return 0;
            return this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)? 1:-1;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(submitTime - System.currentTimeMillis()/1000,TimeUnit.SECONDS);
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public long getTime() {
            return time;
        }

        public void setTime(long time) {
            this.time = time;
        }
    }
}
